<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图导航区域-->
    <el-card>
      <el-alert
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>

      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!--tab页签区-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--动态参数面板-->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!--动态参数表格-->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--循环渲染tag 标签-->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParms(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParamsDialogVisible = true"
            >添加属性</el-button
          >

          <!--静态属性表格-->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--循环渲染tag 标签-->
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delParms(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addDialigClosed"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editDialigClosed"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      selectCateKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addRules: {
        attr_name: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' }
        ]
      },

      editParamsDialogVisible: false,
      editForm: {},
      //修改表单验证规则
      editRules: {
        attr_name: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      let result = await new this.Request(this.Urls.m().getCate).modeGet()
      if (result.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      } else {
        this.cateList = result.data
      }
    },
    handleChange() {
      this.getParamsData()
    },
    handleTabClick() {
      this.getParamsData()
    },
    async getParamsData() {
      console.log(this.selectCateKeys.length)
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = [];
        this.manyTableData=[];
        this.onlyTableData=[];
        return
      } else {
        let result = await new this.Request(
          this.Urls.m().getCate + `/${this.cateId}/attributes`,
          { sel: this.activeName }
        ).modeGet()
        console.log('商品属性', result, this.cateId)
        if (result.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')
        } else {
          console.log('获取参数列表成功', result)

          result.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            //控制文本框的显示与隐藏
            item.inputVisible = false
            //文本框中输入的值
            item.inputValue = ''
          })
          if (this.activeName == 'many') {
            //动态参数
            this.manyTableData = result.data
          } else {
            //静态
            this.onlyTableData = result.data
          }
        }
      }
    },
    addDialigClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        let result = await new this.Request(
          this.Urls.m().getCate + `/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        ).modePost()
        console.log('添加参数', result)
        if (result.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        } else {
          this.$message.success('添加参数成功')
          this.addParamsDialogVisible = false
          this.getParamsData()
        }
      })
    },
    async showEditDialog(attr_id) {
      this.editParamsDialogVisible = true
      let result = await new this.Request(
        this.Urls.m().getCate + `/${this.cateId}/attributes/${attr_id}`,
        { attr_sel: this.activeName }
      ).modeGet()
      if (result.meta.status !== 200) {
        console.log('参数失败', result, attr_id)
        return this.$message.error('获取参数信息失败')
      } else {
        console.log('参数', result, attr_id)
        this.editForm = result.data
      }
    },
    editDialigClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //修改按钮
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        let result = await new this.Request(
          this.Urls.m().getCate +
            `/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        ).modePut()
        if (result.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        } else {
          this.editParamsDialogVisible = false
          this.getParamsData()
          this.$message.success('修改成功')
        }
      })
    },
    //根据id删除对应的参数项
    async delParms(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      //  用户取消了删除操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('用户已取消')
      } else {
        let result = await new this.Request(
          this.Urls.m().getCate + `/${this.cateId}/attributes/${attr_id}`
        ).modeDel()
        if (result.meta.status !== 200) {
          return this.$message.error('删除失败')
        } else {
          this.getParamsData()
          this.$message.success('删除成功')
        }
      }
    },
    //文本框失去焦点，或者摁下了enter都会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      } else {
        //输入了内容 后续处理
        row.attr_vals.push(row.inputValue.trim())
        this.saveAttrValue(row)
        row.inputValue = ''
        row.inputVisible = false
      }
    },
    //点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true
      //$nextTick 方法作用，当页面上元素重新被渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //删除参数
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrValue(row)
    },

    async saveAttrValue(row) {
      //保存操作
      let result = await new this.Request(
        this.Urls.m().getCate + `/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join('')
        }
      ).modePut()

      if (result.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      } else {
        this.$message.success('修改参数项成功')
      }
    }
  },
  computed: {
    isBtnDisable() {
      if (this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId() {
      if (this.selectCateKeys.length == 3) {
        return this.selectCateKeys[2]
      } else {
        return null
      }
    },
    titleText() {
      if (this.activeName == 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
